<template>
  <el-dialog
    :title="`${type === 'Add' ? '新增' : '编辑'}账号`"
    :visible.sync="dialogVisible"
    width="600px"
    custom-class="dialog"
    @close="handleClose"
  >
    <el-form ref="form" size="small" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="姓名" prop="name">
        <el-input v-model="form.name" placeholder="请输入姓名"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入手机号"></el-input>
      </el-form-item>
      <el-form-item v-if="type === 'Add'" label="密码" class="random-password" prop="password">
        <el-input v-model="form.password" />
        <el-button size="small" type="primary" plain @click="genRandomPassword(10)"> 随机密码 </el-button>
      </el-form-item>
      <el-form-item label="角色" prop="roleList">
        <el-select class="full-width" v-model="form.roleList" placeholder="请选择角色">
          <el-option v-for="item in roleOptions" :key="item.id" :label="item.name" :value="item.id"> </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select class="full-width" v-model="form.status" placeholder="请选择状态" clearable>
          <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose" size="small">取 消</el-button>
      <el-button type="primary" size="small" @click="submitForm"> 保 存 </el-button>
    </span>
  </el-dialog>
</template>
<script>
import { getRole, addUser, editUser } from '@/api/user';
export default {
  data() {
    return {
      type: 'Add',
      currentRow: null,
      dialogVisible: false,
      form: {
        name: '',
        phone: '',
        password: '',
        roleList: '',
        status: '',
      },
      roleOptions: [],
      statusOptions: [
        { label: '停用', value: 1 },
        { label: '启用', value: 0 },
      ],
      pageVO: {
        total: 0,
        pageNum: 1,
        pageSize: 10,
      },
      rules: {
        name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
        phone: [{ required: true, message: '手机号不能为空', trigger: 'blur' }],
        password: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
        roleList: [{ required: true, message: '请选择角色', trigger: 'change' }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }],
      },
    };
  },
  created() {
    this.getRole();
  },
  methods: {
    openHandle(type, row) {
      this.type = type;
      this.currentRow = { ...row };
      if (type == 'Edit') {
        this.setFormData(row);
      }
      this.dialogVisible = true;
    },
    setFormData(row) {
      this.form.name = row.name;
      this.form.phone = row.phone;
      this.form.password = row.password;
      this.form.status = row.status;
      this.form.id = row.id;
      this.form.roleList = row?.roles?.[0]?.id;
    },
    handleClose() {
      this.$refs['form'].resetFields();
      this.setFormData({});
      this.dialogVisible = false;
    },
    genRandomPassword(len = 10) {
      let randomString = '';
      const charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*';
      for (let i = 0; i < len; i++) {
        let randomPoz = Math.floor(Math.random() * charSet.length);
        randomString += charSet.substring(randomPoz, randomPoz + 1);
      }
      this.form.password = randomString;
    },
    getRole() {
      const { projectId } = this.$store.getters;
      const parmas = {
        projectId: projectId,
        pageNo: this.pageVO.pageNum,
        pageSize: 1000,
      };
      getRole(parmas).then(res => {
        this.roleOptions = res.data.data;
      });
    },
    submitForm: function () {
      this.$refs['form'].validate(valid => {
        if (valid) {
          const { projectId } = this.$store.getters;
          const submitParams = {
            ...this.form,
          };
          submitParams.projectId = projectId;
          submitParams.roleList = [submitParams.roleList];
          if (this.type === 'Edit') {
            editUser(submitParams).then(response => {
              this.$message.success('修改成功');
              this.dialogVisible = false;
              this.$emit('getList');
            });
          } else {
            addUser(submitParams).then(response => {
              this.$message.success('添加成功');
              this.dialogVisible = false;
              this.$emit('getList');
            });
          }
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.dialog {
  .full-width {
    width: 100%;
  }
  .random-password {
    .el-input {
      width: calc(100% - 90px);
    }
    .el-button {
      margin-left: 10px;
    }
  }
}
</style>
